#include "http.hpp"

std::string WWWROOT = "./wwwroot";


// 把请求报文 回显
std::string RequestStr(const HttpRequest& req)
{
    std::stringstream str;
    str << req._method << " " << req._path << " " << req._version << "\r\n";
    for(auto& ch : req._params)
    {
        str << ch.first << ": " << ch.second << "\r\n";
    }
    for(auto& ch : req._headers)
    {
        str << ch.first << ": " << ch.second << "\r\n";
    }

    str << "\r\n";
    str << req._body;
    // std::cout << "-------------------------" << std::endl;
    // std::cout << str.str() << std::endl;

    return str.str();
}

void Hello(const HttpRequest& req, HttpResponse* rsp)
{
    rsp->SetContent(RequestStr(req), "text/plain");
}

void Login(const HttpRequest& req, HttpResponse* rsp)
{
    // std::cout << "body:[" << req._body << "]\n";
    rsp->SetContent(RequestStr(req), "text/plain");
}
void Put(const HttpRequest& req, HttpResponse* rsp)
{
    std::string pathname = WWWROOT + req._path;
    Util::WriteFile(pathname, req._body);
}
void Del(const HttpRequest& req, HttpResponse* rsp)
{
    rsp->SetContent(RequestStr(req), "text/plain");
}

int main()
{
    HttpServer httpserver(8080);
    httpserver.SetBaseDir(WWWROOT);
    httpserver.SetThreadCount(3);
    httpserver.Get("/hello", Hello);
    httpserver.Post("/login", Login);
    httpserver.Put("/put.txt", Put);
    httpserver.Post("/del.txt", Del);
    httpserver.Listen();

    return 0;
}